package com.quick.proxy.client;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.quick.proxy.client.config.ClientConfig;
import com.quick.proxy.core.config.ProxyConfig;
import com.quick.proxy.core.handler.ChildChannelHandler;
import com.quick.proxy.core.utils.ProxyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Description: 代理客户端启动
 * Author: 吃素不吃肉
 * Date: 2023/7/9
 *
 * @author 吃素不吃肉
 */
@Slf4j
@Component
public class ProxyClient implements ApplicationRunner {
    @Autowired
    private ChildChannelHandler childChannelHandler;
    @Autowired
    private ClientConfig clientConfig;
    @Autowired
    private ProxyConfig proxyConfig;

    public void start() {
        ProxyUtils.createProxyClient(clientConfig.getIp(), clientConfig.getPort(), childChannelHandler);
    }

    @Override
    public void run(ApplicationArguments args) {
        load();
        start();
    }


    private void load() {
        Map<String, Object> config = BeanUtil.beanToMap(proxyConfig);
        config.putAll(BeanUtil.beanToMap(clientConfig));
        for (Map.Entry<String, Object> entry : config.entrySet()) {
            if (entry.getValue() instanceof List) {
                log.info("load config {}:{}", entry.getKey(), JSONUtil.toJsonPrettyStr(entry.getValue()));
            } else {
                log.info("load config {}:{}", entry.getKey(), entry.getValue());
            }
        }
    }
}
